<?php
namespace Home\Controller;
use Think\Controller;

class PaymentController extends Controller
{
    protected $payment;
    /**
     * 提交支付方式
     */
    public function pay()
    {
        $uid = session('user_id');
        $order_id = I('post.order_id');
        // 支付方式码
        $pay_type = to_int(I('post.pay_type'));
        $pay_price = to_int(I("post.pay_price"));
        $order_msg = M('order')->where("order_id = '%s' AND uid = %d", array($order_id, $uid) )->find();
        if ($order_msg) {//如果是自己的订单，才能操作
            if($order_msg['is_pay'] == 1){
                $this->ajaxReturn(array("status" => "error" ,"msg" => "此订单已完成支付"));
            }
            $agent = M('agent')->where( array('agent_id' => $uid) )->find();
            if($pay_type == 0) $this->ajaxReturn(array("status" => "error" ,"msg" => "支付方式有误"));
            $pay_ = M("payment")->where("p_id = %d",array($pay_type))->find();
            // 余额支付
            if($pay_['pay_code'] == "balance")
            {
                //订单的总金额[加上手续费]
                $total = ($order_msg['price'] * 100 + $pay_price*100- $order_msg['discount'] * 100) / 100;
                if ($total > $agent['money']) {
                    $this->ajaxReturn(array("status" => "error" ,"msg" => "预存款不足，请返回充值"));
                } else {
                    // 减去预存款
                    $end_money = ($agent['money'] * 100 - $total * 100) / 100;
                    M('agent')->where( array('agent_id' => $uid) )->save( array('money' => $end_money) );
                    update_pay_status($order_id ,"balance");
                    //更新订单中的支付方式,手续费
                    M('order')->where(array('order_id'=> $order_id))->save(array(
                        'pay_type' => $pay_type,
                        'service_price' => $pay_price
                    ));
                    $content = "用户 " .GetAgentNameById($uid).
                        " 下单：$order_id 扣除预存款"."："."$total 元";
                    wlm_write_log($uid ,$content ,$total ,2);

                    // 支付之后向上级推送消息
                    $parent_id = $agent['parent_id'];
                    if($parent_id != 0){
                        $parent_agent = M('agent')->where(array('agent_id'=>$parent_id))->find();
                        $mes = M('model_message')->where(array('model_name'=>"上级推送通知"))->find();
                        $url = SITE_URL.U("Order/index");
                        $date = date("Y-m-d H:i",time());
                        $data = order_reminder($parent_agent['openid'],$mes['model_id'],$url,$mes['content_begin'],$order_id,$total,$date,$mes['content_end']);
                        Template_message($data);
                        $send_sms = M("config")->where("conf_key = 'order_send_sms'")->getField("conf_value");
                        if($send_sms == 1){
                            $code = array("sn" => $order_id, "amt" => $total, "time" => $date);
                            send_sms($parent_agent['mobile'], $code ,2);
                            send_sms(session('amobile'), $code ,2);
                        }
                    }
                    $this->ajaxReturn(array("status" => "success" ,"reload_page" =>1));
                }
            } else {
                vendor("Payment.{$pay_['pay_code']}.{$pay_['pay_code']}");
                $pay_action = "\\" .$pay_['pay_code'];
                $payment = new $pay_action();
                $user = M("agent")->where("agent_id = %d" ,array(session('user_id')))->find();
                if($pay_['pay_code'] == 'weixin' && $user['openid'] && strstr($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')){
                    $code_str = $payment->getJSAPI( $order_msg);
                    if(isset($code_str["error"])){
                        $this->ajaxReturn(array("status" => "error" ,"msg" => $code_str["error"]));
                    }
                    $this->ajaxReturn(array("status" => "success" ,"msg" => $code_str ,"reload_page" =>2));
                }else{
                    $code_str = $payment->get_code( $order_msg);
                    $this->ajaxReturn(array("status" => "success" ,"msg" => $code_str ,"reload_page" =>2));
                }
                exit;
            }
        } else {
            $this->ajaxReturn(array("status" => "error" ,"msg" => "订单信息有误"));
        }
    }

    // 服务器点对点
    public function notify_alipay()
    {
        vendor("Payment.alipay.alipay");
        $payment = new \alipay();
        $payment->response();
        exit();
    }

    // 服务器点对点
    public function notify_wx()
    {
        vendor("Payment.weixin.weixin");
        $payment = new \weixin();
        $payment->response();
        exit();
    }

    // 页面跳转
    public function returnUrl()
    {
        $pay_code = $_REQUEST['pay_code'] ? I("pay_code") : 'alipay';
        vendor("Payment.{$pay_code}.{$pay_code}");
        $pay_action = "\\" .$pay_code;
        $payment = new $pay_action();
        $result = $payment->respond2();
        if($result['status'] == 1){
            M('order')->where("order_id = '%s'", $result['order_sn'])->save(array('pay_type' => 2, 'is_pay' => 1));
        }
        $order = M('order')->where("order_id = '%s'", $result['order_sn'])->find();
        $this->redirect("Home/Order/order_confirm" ,array("id" => $order['id']));
    }

    // 充值余额
    public function recharge()
    {
        $amt = to_int(I("post.amt"));
        $pay_type = to_int(I("post.pay_type"));
        if(!preg_match("/^[1-9]+[0-9]*$/", $amt) || $amt < 100){
            $this->ajaxReturn(array("status" => "error" ,"msg" => "支付金额有误"));
        }
        $payment = M("payment")->where("p_id = %d",array($pay_type))->find();
        if(!$payment){
            $this->ajaxReturn(array("status" => "error" ,"msg" => "支付方式有误"));
        }
        $pay_code = $payment["pay_code"];
        vendor("Payment.{$pay_code}.{$pay_code}");
        $pay_action = "\\" .$pay_code;
        $payment = new $pay_action();
        $pay_sn = "R".date("YmdHis").rand(1000,9999);
        $pay_msg = array(
            "price" => $amt * 100,
            "discount" => 0,
            "order_id" => $pay_sn
        );
        M('recharge')->add(array("agent_id" => session('user_id'),"amt" => $amt,"r_sn" => $pay_sn));
        $user = M("agent")->where("agent_id = %d" ,array(session('user_id')))->find();
        if($pay_code == 'weixin' && $user['openid']){
            $code_str = $payment->getJSAPI( $pay_msg);
            if(isset($code_str["error"])){
                $this->ajaxReturn(array("status" => "error" ,"msg" => $code_str["error"]));
            }
            $this->ajaxReturn(array("status" => "success" ,"msg" => $code_str));
        }else{
            $code_str = $payment->get_code( $pay_msg);
            $this->ajaxReturn(array("status" => "success" ,"msg" => $code_str));
        }
        exit;
    }
}
